/*
 * CImageWatcher.cpp
 *
 *  Created on: 2018年5月11日
 *      Author: zhengboyuan
 */

#include "CImageWatcher.h"
#include "Path.h"
#include "AppConfig.h"
#include "AppConst.h"
#include <errno.h>
#include "CDataStore.h"
#include "TStringUtil.h"

CImageWatcher::CImageWatcher():
	m_store(new CDataStore())
{
	m_dbPath = getDefaultDbPath();
}

CImageWatcher::~CImageWatcher()
{
	close();
}

void CImageWatcher::setDb(const char* filepath)
{
	if (filepath == NULL || strlen(filepath) == 0)
	{
		return;
	}

	m_dbPath = filepath;
}

bool CImageWatcher::addImageDir(const char* imageDir, const char* urlPath)
{
	if (imageDir == NULL)
	{
		return false;
	}

	std::string mapPath;
	if (urlPath == NULL || strlen(urlPath) == 0)
	{
		mapPath = "/images/" + comn::Path::basename(imageDir);
	}
	else
	{
		mapPath = urlPath;
	}
	return m_httpService.addStatic(imageDir, mapPath);
}

int CImageWatcher::open(uint16_t port, const char* webroot)
{
	if (webroot == NULL)
	{
		webroot = "";
	}

	if (!m_store->open(m_dbPath))
	{
		return ENOENT;
	}

	m_httpService.setDb(m_store);
	m_httpService.start(port, webroot);

	return 0;
}

void CImageWatcher::close()
{
	m_store->close();

	m_httpService.stop();
}

bool CImageWatcher::isOpen()
{
	return m_store->isOpen();
}

bool CImageWatcher::addEvent(EventRecord& record)
{
	return m_store->addEvent(record);
}

bool CImageWatcher::addImage(ImageRecord& record)
{
	return m_store->addImage(record);
}

int CImageWatcher::findImage(const char* company, const char* station, int num, time_t fromTime, time_t toTime, ImageRecord* records, int size)
{
	return m_store->searchImage(company, station, num, fromTime, toTime, records, size);
}

int CImageWatcher::findEvent(const char* company, const char* station, int num, time_t fromTime, time_t toTime, EventRecord* records, int size)
{
	return m_store->searchEvent(company, station, num, fromTime, toTime, records, size);
}

bool CImageWatcher::queryImage(const char* filepath, ImageRecord& record)
{
	return m_store->findImage(filepath, record);
}

bool CImageWatcher::queryEvent(const char* filepath, EventRecord& record)
{
	return m_store->findEvent(filepath, record);
}

bool CImageWatcher::deleteEvent(int id)
{
	return m_store->removeEvent(id);
}

bool CImageWatcher::deleteImage(int id)
{
	return m_store->removeImage(id);
}

std::string CImageWatcher::getDefaultDbPath()
{
	std::string workdir = comn::Path::getWorkDir();
	return comn::Path::join(workdir, AppConst::DB_FILE);
}

bool CImageWatcher::updateEvent(EventRecord& record)
{
	return m_store->updateEvent(record);
}